<!-- components/TemplateDesign.vue -->
<template>
  <div class="template-design">
    <div class="design-toolbar">
      <el-form :model="templateForm" inline>
        <el-form-item label="模板名称">
          <el-input v-model="templateForm.title" style="width: 200px" placeholder="输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型">
          <el-select v-model="templateForm.category" style="width: 200px">
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="templateForm.isPublic" />
        </el-form-item>
        <el-form-item label="模板介绍">
          <el-input
            v-model="templateForm.description"
            style="width: 300px"
            placeholder="输入模板介绍以描述该模板的用途或功能"
          />
        </el-form-item>
      </el-form>

      <el-form :model="templateForm">
        <el-form-item label="模板内容">
          <el-input
            v-model="templateForm.content"
            type="textarea"
            style="width: 100%"
            :rows="6"
            placeholder="使用 {{字段名}} 作为表单字段占位符"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 表单设计器 -->
    <DocumentFormDesigner ref="formDesignerRef" />

    <div class="design-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="previewTemplate">预览</el-button>
      <el-button type="primary" @click="saveTemplate">保存模板</el-button>
    </div>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="模板预览" width="800px">
      <div class="preview-content">
        <h3>{{ templateForm.title }}</h3>
        <div class="preview-text" v-html="previewContent"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, inject } from 'vue'
import { ElMessage } from 'element-plus'
import DocumentFormDesigner from './DocumentFormDesigner.vue'
import { userInfoStore } from '@/stores/userinfo'

const api = inject('$api')
const userStore = userInfoStore()

const props = defineProps({
  currentTemplate: Object,
})

const emit = defineEmits(['save', 'cancel'])

const formDesignerRef = ref()
const previewVisible = ref(false)

// 模板分类选项
const categories = [
  { value: 'contract', label: '合同' },
  { value: 'agreement', label: '协议' },
  { value: 'petition', label: '诉状' },
  { value: 'notice', label: '通知' },
  { value: 'affidavit', label: '宣誓书' },
  { value: 'other', label: '其他' },
]

const templateForm = reactive({
  title: '',
  category: 'contract',
  description: '',
  content: '',
  createdBy: userStore.user?.id,
  isPublic: 1, // 1表示公开，0表示私有
})

// 预览内容
const previewContent = computed(() => {
  let content = templateForm.content
  const formSchema = formDesignerRef.value?.getFormSchema() || []

  formSchema.forEach((field) => {
    const placeholder = `{{${field.model}}}`
    const previewValue = `<span style="color: #409eff; border-bottom: 1px dashed #409eff;">[${field.label}]</span>`
    content = content.replace(new RegExp(placeholder, 'g'), previewValue)
  })

  return content.replace(/\n/g, '<br>')
})

// 初始化编辑模式
onMounted(() => {
  if (props.currentTemplate) {
    // 编辑模式：加载现有模板数据
    Object.assign(templateForm, {
      title: props.currentTemplate.title,
      category: props.currentTemplate.category || 'contract',
      description: props.currentTemplate.description,
      content: props.currentTemplate.content,
      isPublic: props.currentTemplate.is_public ? 1 : 0,
    })
    if (props.currentTemplate.form_schema) {
      formDesignerRef.value?.setFormSchema(props.currentTemplate.form_schema)
    }
  } else {
    // 新建模式：设置默认值
    templateForm.title = ''
    templateForm.category = 'contract'
    templateForm.description = ''
    templateForm.content = ''
    templateForm.isPublic = 1
    formDesignerRef.value?.setFormSchema([])
  }
})

// 预览模板
const previewTemplate = () => {
  if (!templateForm.content) {
    ElMessage.warning('请输入模板内容')
    return
  }
  previewVisible.value = true
}

// 保存模板
const saveTemplate = async () => {
  try {
    if (!templateForm.title) {
      ElMessage.warning('请输入模板名称')
      return
    }

    const formSchema = formDesignerRef.value?.getFormSchema() || []

    const templateData = {
      ...templateForm,
      formSchema: formSchema,
    }

    if (props.currentTemplate) {
      // 更新现有模板
      await api.documentTemplates.updateTemplate(props.currentTemplate.id, templateData)
      ElMessage.success('更新成功')
    } else {
      // 创建新模板
      await api.documentTemplates.createTemplate(templateData)
      ElMessage.success('创建成功')
    }

    emit('save')
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消设计
const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.template-design {
  padding: 20px;
}

.design-toolbar {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.design-actions {
  margin-top: 20px;
  text-align: center;
}

.preview-content {
  max-height: 500px;
  overflow-y: auto;
}

.preview-text {
  line-height: 1.6;
  margin-top: 16px;
}
</style>
